﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Diagnostics;

// Copy http://www.blueedge.nl/weblog/post/WCF-ExceptionHandling-in-Silverlight.aspx

namespace MailRuWrapper.Server.Silverlight
{
    internal class WcfErrorBehavior : IErrorHandler
    {
  
        void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            try
            {
                // Add code here to build faultreason for client based on exception
                var _faultReason = new FaultReason(error.Message);
                var _exceptionDetail = new ExceptionDetail(error);

                // For security reasons you can also decide to not give the ExceptionDetail back to the client or change the message, etc
                var _faultException = new FaultException<ExceptionDetail>(_exceptionDetail, _faultReason, FaultCode.CreateSenderFaultCode(new FaultCode("0")));

                var _messageFault = _faultException.CreateMessageFault();
                fault = Message.CreateMessage(version, _messageFault, _faultException.Action);
            }
            catch
            {
                // Todo log error
            }   
        }
     
        /// <summary>
        /// Handle all WCF Exceptions
        /// </summary>
        bool IErrorHandler.HandleError(Exception ex)
        {
            try
            {
                // Add logging of exception here!
                Debug.WriteLine(ex.ToString());
            }
            catch
            {
                // Todo log error
            }
            
            // return true means we handled the error.
            return true;
        }


    }

    /// <summary>
    /// Оборачивает все исключения в Fault обертку
    /// позволяет передавать полное исключение
    /// и избежать установки FaultContract в сервисе
    /// </summary>
    public sealed class WcfErrorBehaviorAttribute : WcfBehaviorAttributeBase
    {
        public WcfErrorBehaviorAttribute()
            : base(typeof(WcfErrorBehavior))
        {
        }
    }
}


